import requests
import parsel


class ShopRecommendation:
    def __init__(self, name="外婆菜"):
        print(name)
        self.url = f"https://www.dianping.com/search/keyword/344/0_{name}"
        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 Edg/120.0.0.0',
        }
        self.cookies = {
            '_lx_utm': 'utm_source%3Dbing%26utm_medium%3Dorganic',
            '_lxsdk_cuid': '182117ddf1fc8-0174e6028847dd-4c647e53-384000-182117ddf1fc8',
            '_lxsdk': '182117ddf1fc8-0174e6028847dd-4c647e53-384000-182117ddf1fc8',
            'WEBDFPID': '7x93317yu81w5vz0054wwy257y03y0318107z1z73xy97958702wx99w-2003995845181-1688635843949KIKGKAEfd79fef3d01d5e9aadc18ccd4d0c95073644',
            '_hc.v': '1cde0cce-614f-4662-ba6d-60cd73fead9b.1708049442',
            'qruuid': '71ae4647-4e1d-4574-9167-dd71e2cb17b6',
            'dper': '0202c9258c9828f11698a95f036519d5a08e9077cfb20c7b4f2dc8c79b5f86344a6d2138b43d20dade0d8beba3c9dab080d62914cdbe35a9c86300000000ff1d00007e8b778087fe8b54ef676252daf73bc1128e374c89433a8c026d8d80eb05c8e2de873770f8cff79e5737aa6225ebfe1e',
            'll': '7fd06e815b796be3df069dec7836c3df',
            'Hm_lvt_602b80cf8079ae6591966cc70a3940e7': '1708049478',
            'fspop': 'test',
            'cy': '344',
            'cye': 'changsha',
            's_ViewType': '10',
            'Hm_lpvt_602b80cf8079ae6591966cc70a3940e7': '1708053274',
            '_lxsdk_s': '18dafe876e7-ce6-17b-126%7C%7C42',
        }
        self.html = ""

    def get_data(self):
        resp = requests.get(url=self.url, headers=self.headers, cookies=self.cookies)
        resp.encoding = resp.apparent_encoding
        # print(resp.text)   # resp.text 获取响应文本、resp.json()获取响应json、resp.content获取响应内容
        self.html = resp.text

    def parse_data(self):
        # 解析文本  ==>  1、基于解析的parsel  2、基于查找的正则re
        selector = parsel.Selector(text=self.html)
        # .css()   .xpath()   .re()
        shop_name_list = selector.css("a h4::text").getall()   # CSS语法
        return shop_name_list

    def run(self):
        self.get_data()
        shop_name_list = self.parse_data()
        return shop_name_list


def main(name):
    spider = ShopRecommendation(name=name)
    return spider.run()


if __name__ == '__main__':

    spider = ShopRecommendation(name="外婆菜")
    shop_name_list = spider.run()
    # print(shop_name_list)
